package com.john.utils.common;

import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.dictionary.CustomDictionary;
import com.hankcs.hanlp.seg.Segment;
import com.hankcs.hanlp.seg.common.Term;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * hanlp分词工具类
 */
public class HanlpUtils {
    /***
     * hanlp分词
     * @param content 待词内容
     * @param customHanLPDict 自定义分词词组
     */
    public static List<String> getOut(String content, Map<String,String> customHanLPDict){
        content = StringUtil.filterEmoji(content);
        List<String> keys = new ArrayList<>();
        //使用Hanlp分词;允许用户自定义词性字典
        Segment segment = HanLP.newSegment().enableCustomDictionary(true);
        //添加自定义词性(此处添加了一个词做测试；真实业务中是读取字典表中的词并添加到自定义词性)
        //其中"zingyidongwu"是自定义的词性
//        CustomDictionary.add("紫罗兰熊猫","zingyidongwu");
        // 假设map中已经存入了数据
        for (Map.Entry<String, String> entry : customHanLPDict.entrySet()) {
            CustomDictionary.add(entry.getKey(),entry.getValue());
        }
        List<Term> termList = segment.seg(content);
        //遍历分词结果
        for (Term term : termList) {
            String word = term.toString().substring(0, term.length()); //词
            if (!word.isEmpty()) {
                //将词及词性放到Map结果集中
                keys.add(word);
            }
        }
        System.out.println(keys.toString().replace("[","").replace("]",""));
        return keys;
    }

    /***
     * hanlp分词
     * @param content 待词内容
     */
    public static List<String> getOut(String content){
        content = StringUtil.filterEmoji(content);
        List<String> keys = new ArrayList<>();
        List<Term> termList = HanLP.segment(content);
        //遍历分词结果
        for (Term term : termList) {
            String word = term.toString().substring(0, term.length()); //词
            if (!word.isEmpty()) {
                //将词及词性放到Map结果集中
                keys.add(word);
            }
        }
        System.out.println(keys.toString().replace("[","").replace("]",""));
        return keys;
    }


    public static void main(String[] args) {
        Map<String,String> customHanLPDict = new HashMap<>();
        customHanLPDict.put("紫罗兰熊猫","zingyidongwu");
        getOut("我爱吃薯片，它是红薯油炸而来的，紫罗兰熊猫");
    }
}
